<template>
  <div class="project-container">
    <div class="project-box">
      <div class="project-statistics-box">
        <div
          class="project-statistics-left"
          @click="jumpView"
          v-has="'projectCenter:projectView:projectManage'"
        >
          <div>
            <img src="../../assets/images/icon/project_manage_icon.png">
          </div>
          <span>项目管理</span>
        </div>
        <div class="project-statistics-right">
          <div class="statistics-box">
            <div class="statistics-title">项目统计</div>
            <div class="statistics-subtitle">
              <div class="project-in"></div>
              <div>保内项目：{{ statisticsData.indateTotal || 0 }}</div>
            </div>
            <div class="statistics-subtitle">
              <div class="project-out"></div>
              <div>保外项目：{{ statisticsData.outdateTotal || 0 }}</div>
            </div>
          </div>
          <div
            class="statistics-chart"
            id="statisticsChart"
          ></div>
        </div>
      </div>

      <div class="project-total-box">
        <div class="project-total-top">
          <div class="project-total-top-chart">
            <div
              class="total-chart-box"
              id="totalChart"
            ></div>
            <div class="circle-container">
              <div class="circle-box">
                <p>{{ projectTotalData.total || 0 }}</p>
                <p>项目总量</p>
              </div>
            </div>
          </div>
          <div class="project-total-status">
            <div class="run-bgc">
              <span>试运行</span>
              <span>{{ projectTotalData.sendTotal || 0 }}</span>
            </div>
            <div class="pay-bgc">
              <span>已交付</span>
              <span>{{ projectTotalData.debugTotal || 0 }}</span>
            </div>
            <div class="accept-bgc">
              <span>已验收</span>
              <span>{{ projectTotalData.acceptanceTotal || 0 }}</span>
            </div>
            <div class="overdue-bgc">
              <span>已过保</span>
              <span>{{ projectTotalData.warrantyTotal || 0 }}</span>
            </div>
          </div>
        </div>
        <div
          class="project-total-bottom"
          id="typeChart"
        ></div>
      </div>

      <div class="project-map-box">
        <div
          class="map-chart-box"
          id="mapChart"
        ></div>
        <div class="map-type-box">
          <span
            :class="{ active: item.value === mapType }"
            v-for="item in mapOptions"
            :key="item.value"
            @click="changeMap(item.value)"
          >{{ item.name }}</span>
        </div>
      </div>

      <div class="project-distribute-box">
        <div class="distribute-nav-box">
          <van-dropdown-menu active-color="#3378FF">
            <van-dropdown-item
              v-model="typeValue"
              :options="typeOptions"
              @change="changeType"
            />
            <van-dropdown-item
              v-model="areaValue"
              :options="areaOptions"
              @change="changeArea"
            />
          </van-dropdown-menu>
        </div>

        <div class="project-order-list-box">
          <!-- 按地区 -->
          <template v-if="typeValue === 1">
            <div
              class="project-order-item"
              v-for="(item, index) in areaPorjectOrder"
              :key="index"
            >
              <div class="project-order-item-left">
                <span>{{ (index + 1) >= 10 ? (index + 1) : '0' + (index + 1) }}</span>
                <span>{{ item.area }} {{ item.city }}</span>
              </div>
              <span class="project-order-item-right">{{ item.total }}</span>
            </div>
          </template>

          <!-- 按客户 -->
          <template v-if="typeValue === 2">
            <div
              class="project-order-item"
              v-for="(item, index) in customerPorjectOrder"
              :key="index"
            >
              <div class="project-order-item-left">
                <span>{{ (index + 1) >= 10 ? (index + 1) : '0' + (index + 1) }}</span>
                <span>{{ item.customerName }}</span>
              </div>
              <span class="project-order-item-right">{{ item.total }}</span>
            </div>
          </template>

          <!-- 按行业 -->
          <template v-if="typeValue === 3">
            <div
              class="project-order-item"
              v-for="(item, index) in industryProjectOrder"
              :key="index"
            >
              <div class="project-order-item-left">
                <span>{{ (index + 1) >= 10 ? (index + 1) : '0' + (index + 1) }}</span>
                <span>{{ item.industry }}</span>
              </div>
              <span class="project-order-item-right">{{ item.total }}</span>
            </div>
          </template>
        </div>
      </div>
    </div>

    <van-popup
      v-model="showAreaCustomerPopup"
      position="bottom"
      get-container="#app"
      class="customer-popup"
    >
      <p class="customer-area">{{ customerData.name }}（{{ customerData.value }}）</p>
      <ul class="customer-project-container">
        <li
          v-for="(item, index) in areaCustomerData"
          :key="index"
          @click="jumpToManage(item)"
        >{{ item.customerName }}（{{ item.total || 0 }}）</li>
      </ul>
    </van-popup>
  </div>
</template>

<script>
import { DropdownMenu, DropdownItem, Popup } from 'vant';
import * as echarts from 'echarts';
import { BarChart } from 'echarts/charts';
import { PieChart } from 'echarts/charts';
import { MapChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  DatasetComponentOption,
  TransformComponent
} from 'echarts/components';
// 标签自动布局，全局过渡动画等特性
import { LabelLayout, UniversalTransition } from 'echarts/features';
// 引入 Canvas 渲染器，注意引入 CanvasRenderer 或者 SVGRenderer 是必须的一步
import { CanvasRenderer } from 'echarts/renderers';

// 注册必须的组件
echarts.use([
  TitleComponent,
  TooltipComponent,
  GridComponent,
  DatasetComponent,
  TransformComponent,
  BarChart,
  PieChart,
  MapChart,
  LabelLayout,
  UniversalTransition,
  CanvasRenderer
]);

import optionData from './js/chartOptions';
import '../../../node_modules/echarts/map/js/world';
import '../../../node_modules/echarts/map/js/china';
import {
  getWarrantyPercent,
  getProjectCount,
  getCustomerCount,
  getAreaProjectCount,
  getAreaCustomertCount,
  getAreaProjectOrder,
  getCustomerProjectOrder,
  getIndustryProjectOrder
} from '@/api/projectView';
export default {
  components: {
    [DropdownMenu.name]: DropdownMenu,
    [DropdownItem.name]: DropdownItem,
    [Popup.name]: Popup
  },
  data() {
    return {
      statisticsData: {},
      projectTotalData: {},
      mapType: 0,
      mapOptions: [
        {
          name: '国内分布',
          value: 0
        },
        {
          name: '全球分布',
          value: 1
        }
      ],
      showType: false,
      typeValue: 1,
      typeOptions: [
        //类型选项
        {
          text: '按地区',
          value: 1
        },
        {
          text: '按客户',
          value: 2
        },
        {
          text: '按行业',
          value: 3
        }
      ],
      showArea: false,
      areaValue: 0,
      areaOptions: [
        //地区选项
        {
          text: '全国分布',
          value: 0
        },
        {
          text: '全球分布',
          value: 1
        }
      ],
      areaPorjectOrder: [],
      customerPorjectOrder: [],
      industryProjectOrder: [],
      showAreaCustomerPopup: false,
      customerData: {},
      areaCustomerData: []
    };
  },
  created() {
    this.$toast.clear();
  },
  mounted() {
    this.getWarrantyPercent();
    this.getProjectCount();
    this.getCustomerCount();
    this.getAreaProjectCount(0);
    this.getAreaProjectCount(1);
    this.getAreaProjectOrder(0);
  },
  methods: {
    // 跳转至项目管理
    jumpView() {
      this.$router.push({
        name: 'projectManage'
      });
    },
    // 获取项目质保期数量比例 项目统计
    getWarrantyPercent() {
      getWarrantyPercent().then(res => {
        let { indatePercent, indateTotal, outdatePercent, outdateTotal } = res.data;
        let seriesData = optionData.guaranteeOption.series[0].data;

        seriesData.map(item => {
          switch (item.name) {
            case '保内':
              item.value = indatePercent;
              break;
            case '保外':
              item.value = outdatePercent;
              break;
          }
        });

        this.statisticsData = {
          indateTotal,
          outdateTotal
        };

        this.createStatisticsChart();
      });
    },
    // 获取项目总量
    getProjectCount() {
      getProjectCount().then(res => {
        let { total, sendTotal, debugTotal, acceptanceTotal, warrantyTotal } = res.data;
        let seriesData = optionData.totalOption.series[0].data;
        seriesData.map(item => {
          switch (item.name) {
            case '试运行':
              item.value = sendTotal;
              break;
            case '已交付':
              item.value = debugTotal;
              break;
            case '已验收':
              item.value = acceptanceTotal;
              break;
            case '已过保':
              item.value = warrantyTotal;
              break;
          }
        });
        this.projectTotalData = {
          total,
          sendTotal,
          debugTotal,
          acceptanceTotal,
          warrantyTotal
        };
        this.createTotalChart();
      });
    },
    // 项目设备类型统计
    getCustomerCount() {
      getCustomerCount().then(res => {
        let data = res.data.list;
        let deviceData = [];
        let customerData = [];
        data.map(item => {
          deviceData.push(item.deviceTotal || 0);
          customerData.push(item.customerTotal || 0);
        });

        optionData.deviceAllOption.series[0].data = deviceData;
        optionData.deviceAllOption.series[1].data = customerData;

        this.createTypeChart();
      });
    },
    // 获取地区项目总数
    getAreaProjectCount(areaType) {
      getAreaProjectCount({
        areaType
      }).then(res => {
        if (res.data && res.data.length) {
          if (areaType === 0) {
            // 国内
            res.data.map(areaItem => {
              optionData.chinaOption.series[0].data.map(item => {
                if (item.name === areaItem.area) {
                  item.value = areaItem.total;
                }
              });
            });
          } else {
            // 全球
            res.data.map(areaItem => {
              optionData.mapOption.series[0].data.map(item => {
                if (item.name === areaItem.area) {
                  item.value = areaItem.total;
                }
              });
            });
          }

          this.createMapChart(this.mapType);
        }
      });
    },
    // 项目统计
    createStatisticsChart() {
      // 基于准备好的dom，初始化echarts实例
      let statisticsChart = echarts.init(document.getElementById('statisticsChart'));
      // 绘制图表
      statisticsChart.setOption(optionData.guaranteeOption);
    },
    // 项目总量图
    createTotalChart() {
      // 基于准备好的dom，初始化echarts实例
      let totalChart = echarts.init(document.getElementById('totalChart'));
      totalChart.clear();
      // 绘制图表
      totalChart.setOption(optionData.totalOption);
    },
    // 设备类型图
    createTypeChart() {
      // 基于准备好的dom，初始化echarts实例
      let typeChart = echarts.init(document.getElementById('typeChart'));
      typeChart.clear();
      // 绘制图表
      typeChart.setOption(optionData.deviceAllOption);
    },
    // 地区分布
    createMapChart(type) {
      let mapChart = echarts.init(document.getElementById('mapChart'));
      mapChart.clear();
      if (type === 0) {
        // 国内
        mapChart.setOption(optionData.chinaOption);
      } else {
        // 全球
        mapChart.setOption(optionData.mapOption);
      }
      mapChart.off('click');
      mapChart.on('click', params => {
        console.log('点击了地图---', params);
        this.customerData = params.data;
        if (this.customerData.value) {
          this.areaCustomerData = [];
          if (type === 0) {
            // 国内
            getAreaCustomertCount({
              country: '中国',
              province: params.data.name
            }).then(res => {
              this.areaCustomerData = res.data || [];
              this.showAreaCustomerPopup = true;
              // const el = document.getElementById('chinaCustomerNameBox');
              // let html = ``;
              // res.data.forEach(item => {
              //   html += `<li>${item.customerName}（${item.total || 0}）</li>`;
              // });
              // el.innerHTML = html;
            });
          } else {
            // 全球
            getAreaCustomertCount({
              country: params.data.name
            }).then(res => {
              this.areaCustomerData = res.data || [];
              this.showAreaCustomerPopup = true;
              // const el = document.getElementById('worldCustomerNameBox');
              // let html = ``;
              // res.data.forEach(item => {
              //   html += `<li>${item.customerName}（${item.total || 0}）</li>`;
              // });
              // el.innerHTML = html;
            });
          }
        }
      });
    },
    // 切换地图
    changeMap(type) {
      this.mapType = type;
      this.createMapChart(type);
    },
    // 选择类型
    changeType(value) {
      this.typeValue = value;
      switch (value) {
        // 地区
        case 1:
          this.getAreaProjectOrder(this.areaValue);
          break;
        // 客户
        case 2:
          this.getCustomerProjectOrder(this.areaValue);
          break;
        // 行业
        case 3:
          this.getIndustryProjectOrder(this.areaValue);
          break;
      }
    },
    // 选择地区
    changeArea(value) {
      this.areaValue = value;
      switch (this.typeValue) {
        // 地区
        case 1:
          this.getAreaProjectOrder(this.areaValue);
          break;
        // 客户
        case 2:
          this.getCustomerProjectOrder(this.areaValue);
          break;
        // 行业
        case 3:
          this.getIndustryProjectOrder(this.areaValue);
          break;
      }
    },
    // 按地区排列项目总量
    getAreaProjectOrder(areaType) {
      getAreaProjectOrder({
        areaType
      }).then(res => {
        this.areaPorjectOrder = res.data || [];
      });
    },
    // 按客户排列项目总量
    getCustomerProjectOrder(areaType) {
      getCustomerProjectOrder({
        areaType
      }).then(res => {
        this.customerPorjectOrder = res.data || [];
      });
    },
    // 按客户排列项目总量
    getIndustryProjectOrder(areaType) {
      getIndustryProjectOrder({
        areaType
      }).then(res => {
        this.industryProjectOrder = res.data || [];
      });
    },
    // 跳转至项目管理列表页
    jumpToManage(item) {
      if (this.$checkBtnPermission('projectCenter:projectView:projectManage')) {
        this.$router.push({
          name: 'projectManage',
          query: {
            from: 'projectView',
            customerInfo: {
              id: item.customerId,
              customer: item.customerName
            }
          }
        });
      } else {
        this.$toast('暂无查看项目权限，请联系管理员开通');
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.project-container {
  width: 100%;
  height: 100%;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;

  .project-box {
    padding-bottom: 0.213333rem;

    .tooltip-box {
      width: 8rem;
      padding: 0.4rem;
      font-size: 0.4rem;
      color: #333333;
      background-color: #fff;
    }

    .project-statistics-box {
      display: flex;
      width: 100%;
      height: 2.72rem;
      margin-bottom: 0.213333rem;
      overflow: hidden;

      .project-statistics-left {
        flex-shrink: 0;
        display: flex;
        flex-direction: column;
        justify-content: center;
        align-items: center;
        width: 2.986667rem;
        height: 100%;
        margin-right: 0.213333rem;
        background-color: #fff;

        div {
          display: flex;
          justify-content: center;
          align-items: center;
          width: 1.12rem;
          height: 1.12rem;
          margin-bottom: 0.213333rem;
          border-radius: 0.48rem;
          background-color: #6ad7d1;

          img {
            width: 0.533333rem;
            height: 0.533333rem;
          }
        }

        span {
          font-size: 0.346667rem;
          color: #333333;
        }
      }

      .project-statistics-right {
        flex: 1;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0.426667rem;
        background-color: #fff;

        .statistics-box {
          .statistics-title {
            position: relative;
            padding-left: 0.213333rem;
            color: #3378ff;
            font-size: 0.373333rem;

            &::before {
              content: '';
              position: absolute;
              top: 1px;
              left: 0;
              width: 0.053333rem;
              height: 0.32rem;
              background-color: #3378ff;
            }
          }

          .statistics-subtitle {
            display: flex;
            align-items: center;
            margin-top: 0.16rem;
            font-size: 0.32rem;
            color: #666666;

            .project-in,
            .project-out {
              width: 0.266667rem;
              height: 0.266667rem;
              margin-right: 0.106667rem;
              border-radius: 0.053333rem;
            }

            .project-in {
              background-color: #51b9f4;
            }

            .project-out {
              background-color: #f9ba5d;
            }
          }
        }

        .statistics-chart {
          flex-shrink: 0;
          width: 1.813333rem;
          height: 1.813333rem;
          overflow: hidden;
        }
      }
    }

    .project-total-box {
      width: 100%;
      height: 10.4rem;
      margin-bottom: 0.213333rem;
      padding: 0.426667rem 0;
      background-color: #fff;

      .project-total-top {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 0.64rem;
        padding: 0 0.426667rem;

        .project-total-top-chart {
          position: relative;
          width: 3.466667rem;
          height: 3.466667rem;
          overflow: hidden;

          .total-chart-box {
            width: 100%;
            height: 100%;
          }

          .circle-container {
            position: absolute;
            top: 0;
            left: 0;
            display: flex;
            justify-content: center;
            align-items: center;
            width: 100%;
            height: 100%;

            .circle-box {
              display: flex;
              flex-direction: column;
              justify-content: center;
              align-items: center;
              width: 2.666667rem;
              height: 2.666667rem;
              border-radius: 50%;
              background-color: #d8fdff;

              p {
                &:first-of-type {
                  margin-bottom: 0.266667rem;
                  color: #143066;
                  font-size: 0.64rem;
                }
                &:last-of-type {
                  color: #2454b3;
                  font-size: 0.32rem;
                }
              }
            }
          }
        }

        .project-total-status {
          flex: 1;
          display: flex;
          flex-wrap: wrap;
          margin-left: 0.213333rem;

          div {
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            width: 2.506667rem;
            height: 1.76rem;
            margin-left: 0.213333rem;
            margin-bottom: 0.213333rem;
            color: #fff;
            border-radius: 0.106667rem;
            background-color: #f2f2f2;

            &:nth-of-type(3),
            &:nth-of-type(4) {
              margin-bottom: 0;
            }

            &.run-bgc {
              background-color: #6de49d;
            }

            &.pay-bgc {
              background-color: #8987ff;
            }

            &.accept-bgc {
              background-color: #5bbdf3;
            }

            &.overdue-bgc {
              background-color: #6ad7d1;
            }

            span {
              &:first-of-type {
                margin-bottom: 0.213333rem;
                font-size: 0.32rem;
              }
              &:last-of-type {
                font-size: 0.426667rem;
              }
            }
          }
        }
      }

      .project-total-bottom {
        width: 100%;
        height: 5.173333rem;
      }
    }

    .project-map-box {
      position: relative;
      width: 100%;
      height: 10.533333rem;
      margin-bottom: 0.213333rem;
      padding: 0.133333rem;
      background-color: #fff;

      .map-chart-box {
        width: 100%;
        height: 100%;
      }

      .map-type-box {
        position: absolute;
        top: 0.853333rem;
        left: 0.586667rem;
        display: flex;
        width: 3.626667rem;
        height: 0.693333rem;
        border: 1px solid #ebeef5;
        border-radius: 0.08rem;
        overflow: hidden;

        span {
          flex: 1;
          display: flex;
          justify-content: center;
          align-items: center;
          color: #999999;
          font-size: 0.32rem;

          &.active {
            color: #fff;
            background-color: #3378ff;
          }
        }
      }
    }

    .project-distribute-box {
      width: 100%;
      margin-bottom: 0.32rem;
      background-color: #fff;

      .distribute-nav-box {
        display: flex;
        width: 100%;
        height: 1.066667rem;
        border-bottom: 1px solid #f2f6fc;

        ::v-deep .van-dropdown-menu {
          width: 100%;

          .van-dropdown-menu__bar {
            height: 100%;
          }
        }
      }

      .project-order-list-box {
        width: 100%;
        min-height: 5.333333rem;
        padding: 0 0.426667rem;

        .project-order-item {
          display: flex;
          justify-content: space-between;
          align-items: center;
          padding: 0.32rem 0;
          font-size: 0.373333rem;

          &:not(:last-child) {
            border-bottom: 1px solid #f2f6fc;
          }

          .project-order-item-left {
            margin-right: 0.213333rem;

            span {
              &:first-of-type {
                margin-right: 0.213333rem;
                color: #cccccc;
                font-weight: bold;
              }
              &:last-of-type {
                // line-height: 0.533333rem;
                color: #333333;
              }
            }
          }

          .project-order-item-right {
            color: #666666;
          }
        }
      }
    }
  }
}
</style>

<style lang="scss">
.customer-popup {
  &.van-popup--bottom {
    max-height: 60%;
    border-top-left-radius: 0.426667rem;
    border-top-right-radius: 0.426667rem;

    .customer-area {
      padding: 0.32rem 0.426667rem 0;
      font-size: 0.4rem;
    }

    .customer-project-container {
      padding: 0.266667rem 0.426667rem;

      li {
        line-height: 0.533333rem;
        padding: 0.32rem 0;
        font-size: 0.346667rem;
        border-bottom: 1px solid var(--border-color);

        &:last-of-type {
          border-bottom: 0;
        }
      }
    }
  }
}
</style>
